package com.goods.business.service.imp;

import com.goods.business.mapper.BizConsumerMapper;
import com.goods.business.mapper.BizOutStockInfoMapper;
import com.goods.business.mapper.BizOutStockMapper;
import com.goods.business.mapper.BizProductMapper;
import com.goods.business.service.BizOutStockService;
import com.goods.common.model.business.*;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.business.*;
import com.goods.common.vo.system.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
@Transactional
public class BizOutStockServiceImpl implements BizOutStockService {

    @Autowired
    private BizOutStockMapper bizOutStockMapper;
    @Autowired
    private BizOutStockInfoMapper bizOutStockInfoMapper;
    @Autowired
    private BizConsumerMapper bizConsumerMapper;
    @Autowired
    private BizProductMapper bizProductMapper;
    @Override
    public PageVO<OutStockVO> findOutStockList(Map<String, Object> queryMap) {
        Example example = new Example(BizOutStock.class);
        Example.Criteria criteria = example.createCriteria();
        if (queryMap.containsKey("inNum") && !queryMap.get("inNum").equals(""))
            criteria.andEqualTo("inNum", queryMap.get("inNum"));//入库单
        if (queryMap.containsKey("type") && !queryMap.get("type").equals(""))
            criteria.andEqualTo("type", queryMap.get("type"));//入库类别
        if (!queryMap.get("status").equals(""))
            criteria.andEqualTo("status", queryMap.get("status"));//逻辑删除
        // TODO: 2021/9/25 解决时间问题
        if (queryMap.containsKey("startTime") && queryMap.get("startTime").equals(""))
            criteria.andBetween("createTime", queryMap.get("startTime"), queryMap.get("endTime"));

        List<BizOutStock> bizOutStocks = bizOutStockMapper.selectByExample(example);
        List<OutStockVO> outStockVOS = new ArrayList<>();
        for (BizOutStock bizOutStock : bizOutStocks) {
            OutStockVO outStockVO = new OutStockVO();
            BeanUtils.copyProperties(bizOutStock, outStockVO);
            //设置物资去向
            BizConsumer bizConsumer = bizConsumerMapper.selectByPrimaryKey(bizOutStock.getConsumerId());
            if (bizConsumer != null){
                outStockVO.setOperator(bizOutStock.getOperator());
                outStockVO.setAddress(bizConsumer.getAddress());
                outStockVO.setContact(bizConsumer.getContact());
                outStockVO.setPhone(bizConsumer.getPhone());
                outStockVO.setName(bizConsumer.getName());
                outStockVO.setSort(bizConsumer.getSort());
            }
            outStockVOS.add(outStockVO);
        }
        List<OutStockVO> page =null;
        if (queryMap.get("pageNum") != null && queryMap.get("pageSize") != null) {
            page = ListPageUtils.page(outStockVOS, Integer.parseInt((String) queryMap.get("pageSize")), Integer.parseInt((String) queryMap.get("pageNum")));
            return new PageVO<OutStockVO>(outStockVOS.size(), page);
        }
        return new PageVO<OutStockVO>(outStockVOS.size(), outStockVOS);
    }

    @Override
    public void saveStock(OutStockVO outStockVO) {
        BizOutStock bizOutStock = new BizOutStock();
        //检查有没有消费者,存在就把id设置进去，不存在就创建一个返回主键id
        Long consumerId = outStockVO.getConsumerId();
        if (consumerId == null)
          consumerId = this.packConsumer(outStockVO);
        bizOutStock.setConsumerId(consumerId);

        String outNum = UUID.randomUUID().toString().substring(0, 32);
        bizOutStock.setOutNum(outNum);

        // TODO: 2021/9/25 批量处理
        List<Object> products = outStockVO.getProducts();
        if (!CollectionUtils.isEmpty(products)){
            //产品不为空
            for (Object product : products) {
                Map<String, Object> map = (Map<String, Object>) product;
                Object productId = map.get("productId");
                Object productNumber = map.get("productNumber");
                BizProduct bizProduct = bizProductMapper.selectByPrimaryKey(productId);
                if (bizProduct != null){
                    BizOutStockInfo bizOutStockInfo = new BizOutStockInfo();
                    bizOutStockInfo.setCreateTime(new Date());
                    bizOutStockInfo.setModifiedTime(new Date());
                    bizOutStockInfo.setOutNum(outNum);
                    bizOutStockInfo.setpNum(bizProduct.getpNum());
                    bizOutStockInfo.setProductNumber((Integer) productNumber);
                    bizOutStockInfoMapper.insert(bizOutStockInfo); //保存入库详情
                }
            }
            bizOutStock.setProductNumber(products.size());
        }

        //其他参数
        bizOutStock.setType(outStockVO.getType());
        bizOutStock.setOperator(outStockVO.getOperator());
        bizOutStock.setCreateTime(new Date());
        bizOutStock.setPriority(outStockVO.getPriority());
        bizOutStock.setRemark(outStockVO.getRemark());
        bizOutStock.setStatus(outStockVO.getStatus()==null?2:outStockVO.getStatus()); //设置状态为待审核

        bizOutStockMapper.insert(bizOutStock);
    }

    private Long packConsumer(OutStockVO outStockVO) {
        BizConsumer bizConsumer = new BizConsumer();//创建一个新的，返回id
        bizConsumer.setName(outStockVO.getName());
        bizConsumer.setAddress(outStockVO.getAddress());
        bizConsumer.setCreateTime(new Date());
        bizConsumer.setModifiedTime(new Date());
        bizConsumer.setPhone(outStockVO.getPhone());
        bizConsumer.setContact(outStockVO.getContact());
        bizConsumer.setSort(outStockVO.getSort());
        bizConsumerMapper.insert(bizConsumer);
        return bizConsumer.getId();
    }


    @Override
    public OutStockDetailVO findOutStockDetailById(Long id, Integer pageNum) {
        OutStockDetailVO outStockDetailVO = new OutStockDetailVO();

        //查询出库信息
        BizOutStock bizOutStock = bizOutStockMapper.selectByPrimaryKey(id);

        //获取消费者信息
        BizConsumer bizConsumer = bizConsumerMapper.selectByPrimaryKey(bizOutStock.getConsumerId());
        if (bizConsumer != null){
            ConsumerVO consumerVO = new ConsumerVO();
            BeanUtils.copyProperties(bizConsumer, consumerVO);
            outStockDetailVO.setConsumerVO(consumerVO);
        }else {
            outStockDetailVO.setConsumerVO(null);
        }
        //获取出库商品信息
        Example example = new Example(BizOutStockInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("outNum", bizOutStock.getOutNum());
        List<BizOutStockInfo> bizOutStockInfos = bizOutStockInfoMapper.selectByExample(example);
        List<OutStockItemVO> outStockItemVOS = new ArrayList<>();
        for (BizOutStockInfo bizOutStockInfo : bizOutStockInfos) {
            OutStockItemVO outStockItemVO = new OutStockItemVO();
            Example example1 = new Example(BizProduct.class);
            example1.createCriteria().andEqualTo("pNum", bizOutStockInfo.getpNum());
            BizProduct bizProduct = bizProductMapper.selectOneByExample(example1);
            example1.clear();
            BeanUtils.copyProperties(bizProduct, outStockItemVO);
            outStockItemVOS.add(outStockItemVO);
        }
        outStockDetailVO.setItemVOS(outStockItemVOS);
        outStockDetailVO.setOutNum(bizOutStock.getOutNum());
        outStockDetailVO.setStatus(bizOutStock.getStatus());
        outStockDetailVO.setType(bizOutStock.getType());
        outStockDetailVO.setOperator(bizOutStock.getOperator());
        outStockDetailVO.setTotal(bizOutStock.getProductNumber());

        return outStockDetailVO;
    }

    @Override
    public void updateStatus(Integer id, int status) {
        BizOutStock bizOutStock = bizOutStockMapper.selectByPrimaryKey(id);
        if (bizOutStock !=null){
            bizOutStock.setStatus(status);
            bizOutStockMapper.updateByPrimaryKey(bizOutStock);
        }
    }

    @Override
    public void deleteById(Integer id) {
        //先查寻出详情
        BizOutStock bizOutStock = bizOutStockMapper.selectByPrimaryKey(id);
        //获取outNum,删除info的信息
        Example example = new Example(BizOutStockInfo.class);
        example.createCriteria().andEqualTo("outNum", bizOutStock.getOutNum());
        bizOutStockInfoMapper.deleteByExample(example);
        bizOutStockMapper.deleteByPrimaryKey(id);
    }
}
